#!/bin/bash

# Agent 5 Task 3: Compile All Files
# This script compiles all 11 .cpp files and logs results

OUTPUT_DIR="/home/linden/claude/zclaude/conversion-evaluation/12-phase3-fixes"
RUNTIME_SHIMS="/home/linden/claude/zclaude/cpp-orchestrator/src/orchestrator/runtime_shims"

mkdir -p "$OUTPUT_DIR/logs"

echo "============================================================"
echo "Phase 3 Compilation Validation"
echo "============================================================"
echo ""

SUCCESS_COUNT=0
FAILURE_COUNT=0
TOTAL_COUNT=0

# Array of all .cpp files (relative to their directories)
declare -a files=(
    "C5/c5/array_list.cpp"
    "C5/c5/hash_set.cpp"
    "DelegateTransform/ktsu/delegate_transform/delegate_transform.cpp"
    "DelegateTransform/ktsu/delegate_transform/test/delegate_transform_tests.cpp"
    "DotNetCSharpLinqByExample/linq_lib/pet.cpp"
    "DotNetCSharpLinqByExample/linq_lib_test/joins.cpp"
    "RobloxAPI/roblox_api/group.cpp"
    "RobloxAPI/roblox_api/group_role.cpp"
    "RobloxAPI/roblox_api/http_helper.cpp"
    "RobloxAPI/roblox_api/outfit.cpp"
    "RobloxAPI/roblox_api/search_api.cpp"
)

for file in "${files[@]}"; do
    TOTAL_COUNT=$((TOTAL_COUNT + 1))

    # Extract directory and basename
    DIR=$(dirname "$file")
    BASENAME=$(basename "$file" .cpp)

    echo "[$TOTAL_COUNT/11] Compiling: $file"

    # Compile with g++ C++20
    cd "/home/linden/claude/zclaude/conversion-evaluation/10-final-generation"

    # Set include paths - need parent directories for namespace includes
    INCLUDES="-I. -I$DIR/.. -I$RUNTIME_SHIMS"

    g++ -std=c++20 -c "$file" \
        $INCLUDES \
        2>&1 | tee "$OUTPUT_DIR/logs/${BASENAME}.log"

    # Check result
    if [ ${PIPESTATUS[0]} -eq 0 ]; then
        echo "  ✓ SUCCESS"
        SUCCESS_COUNT=$((SUCCESS_COUNT + 1))
        echo "SUCCESS" > "$OUTPUT_DIR/logs/${BASENAME}.result"
    else
        echo "  ✗ FAILED"
        FAILURE_COUNT=$((FAILURE_COUNT + 1))
        echo "FAILED" > "$OUTPUT_DIR/logs/${BASENAME}.result"
    fi

    cd - > /dev/null
    echo ""
done

# Calculate success rate
SUCCESS_RATE=$(echo "scale=1; $SUCCESS_COUNT * 100 / $TOTAL_COUNT" | bc)

echo "============================================================"
echo "Compilation Results"
echo "============================================================"
echo "Total files:    $TOTAL_COUNT"
echo "Successful:     $SUCCESS_COUNT"
echo "Failed:         $FAILURE_COUNT"
echo "Success rate:   $SUCCESS_RATE%"
echo ""
echo "Baseline:       18.2% (2/11 files)"
echo "Target:         ≥80% (9/11 files)"
echo ""

if (( $(echo "$SUCCESS_RATE >= 80" | bc -l) )); then
    echo "Status: ✓ TARGET MET"
elif (( $(echo "$SUCCESS_RATE >= 70" | bc -l) )); then
    echo "Status: ⚠ CLOSE - Consider iteration"
else
    echo "Status: ✗ BELOW TARGET"
fi

echo "============================================================"
echo ""
echo "Logs saved to: $OUTPUT_DIR/logs/"
